//
//  DownLoadViewController.m
//  HuateVideo
//
//  Created by jun yuan on 12-9-1.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
//下载状态码，0正在下载、1正在等待、2已暂停、3下载失败
#import "DownLoadViewController.h"
#import "DownLoadingCell.h"
#import "UserDefaults.h"
#import "PicShowViewController.h"
@interface DownLoadViewController ()

@end

@implementation DownLoadViewController
static ASIHTTPRequest* currentRequest=nil;
static NSInteger currentIndex=0;
#pragma mark downMovie
-(void)downMovie:(NSNotification*)notify{
    
    id m=[notify object];
    Movie*mov=(Movie*)m;
     NSLog(@"%@",mov.File_path_array);
    if ([m detailType]!=MovieChannelTypeSeries) {
        if ([self chechMovie:mov]) {
            UIAlertView* u=[[UIAlertView alloc] initWithTitle:LS(@"提示") 
                                                      message:LS(@"已在下载列表中")
                                                     delegate:nil 
                                            cancelButtonTitle:LS(@"确定") 
                                            otherButtonTitles:nil];
            [u show];
            [u release];
            return;
        } else{
            [mov setStatusCode:1];
            [downloadArray addObject:mov];
        }
    }else {
         NSLog(@"Series");
        NSArray* Series=[self deliverSeries:mov];
        BOOL b_has=NO;
        for ( int i=0;i<Series.count;i++) {
            Movie*m=(Movie*)[Series objectAtIndex:i];
           b_has=[self chechMovie:m];
            if (b_has) {
                break;
            }else{
                m.statusCode=1;
                [downloadArray addObject:m];
            }
        }
        if (b_has) {
            UIAlertView* u=[[UIAlertView alloc] initWithTitle:LS(@"提示") 
                                                      message:LS(@"已在下载列表中")
                                                     delegate:nil 
                                            cancelButtonTitle:LS(@"确定") 
                                            otherButtonTitles:nil];
            [u show];
            [u release];
            return;
        }else{
        
        }
    }
    
    [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
    if (![self hasDownloadingMovie]) {
        Movie*t;
        if (mov.detailType==MovieChannelTypeSeries) {
            t=[downloadArray objectAtIndex:0];
        }else{
            t=mov;
        }
        [self startDownload:t];
    }

    [downloadTable reloadData];
    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:LS(@"提示") 
                                              message:LS(@"已加入下载列表")
                                             delegate:nil 
                                    cancelButtonTitle:LS(@"确定") 
                                    otherButtonTitles:nil];
    [alert show];
    [alert release];
}

- (NSArray*)deliverSeries:(Movie*)movie{
    NSArray* array=[movie File_path_array];
    NSMutableArray* newArray=[[NSMutableArray alloc] init];
    Movie* m=nil;
    for (int i=0; i<array.count; i++) {
        if (i%2==0) {//下载地址
            m=[[Movie alloc] initwithMovie:movie];
            NSString* num=[array objectAtIndex:i];
            m.News_title=[NSString stringWithFormat:@"%@(%@%@%@)",movie.News_title,LS(@"第"),num,LS(@"集")];
        }else{//集数
            m.File_path=[array objectAtIndex:i];
            [newArray addObject:m];
            [m release];
            m=nil;
        }
    }
    return [newArray autorelease];
}

- (BOOL)hasDownloadingMovie{
    for (Movie* mov in downloadArray) {
        if (mov.statusCode==0) {
            return YES;
        }
    }
    return NO;
}
-(void)startDownload:(Movie*)movie{
    if (currentRequest==nil) {
        currentIndex=[downloadArray indexOfObject:movie];
        movie.statusCode=0;
          NSLog(@"replaceObjectAtIndex 1");
        [downloadArray replaceObjectAtIndex:currentIndex withObject:movie];
        [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];

        currentMovie=movie;
        currentRequest=[[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:[movie File_path]]];
        currentRequest.delegate = self;//代理
        [currentRequest setDownloadDestinationPath:[self destPath:[movie File_path]]];//下载路径
        [currentRequest setTemporaryFileDownloadPath:[self tempPath:[movie File_path]]];//缓存路径
        [currentRequest setAllowResumeForFileDownloads:YES];//断点续传
      DownLoadingCell*cell =(DownLoadingCell*) [downloadTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentIndex inSection:0]];
        if (cell) {
            currentRequest.downloadProgressDelegate = self;//下载进度代理
        }
        [currentRequest start];
    }
//    else {
//        movie.statusCode=2;
//        [currentRequest clearDelegatesAndCancel];
//        currentRequest=nil;
//    }
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders{
    double movieLength = (double)request.contentLength/1024.0/1024.0;
    currentMovie.movieContentLength=movieLength;
    currentMovie.storePath=[self destPath:[currentMovie File_path]];
     NSLog(@"replaceObjectAtIndex 2");

    [downloadArray replaceObjectAtIndex:currentIndex withObject:currentMovie];
    [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
//	int row=[downloadArray indexOfObject:currentMovie];
//    DownLoadingCell *cell = (DownLoadingCell*)[downloadTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    [currentRequest setDownloadProgressDelegate:self];
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    currentMovie.statusCode=3;
     NSLog(@"replaceObjectAtIndex 3");
    [downloadArray replaceObjectAtIndex:currentIndex withObject:currentMovie];
    [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
    
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    [[NSNotificationCenter defaultCenter] postNotificationName:DOWNLOADED_NOTIFICATION object:currentMovie];
//    [finishedArray addObject:currentMovie];
    [downloadArray removeObject:currentMovie];
//    [UserDefaults setObject:finishedArray forKey:DOWNLOADED_LIST];
    [currentRequest clearDelegatesAndCancel];
    currentRequest=nil;
    if (downloadArray.count) {
        Movie*m=[downloadArray objectAtIndex:0];
        [self startDownload:m];
    }
//    [finishedTable reloadData];
    [downloadTable reloadData];
}
#pragma mark progress
- (void)setProgress:(float)newProgress
{
     NSLog(@"newProgress  %f",newProgress);
	int row=[downloadArray indexOfObject:currentMovie];
    DownLoadingCell *cell = (DownLoadingCell*)[downloadTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    cell.progressView.progress=newProgress;
//	double size=[self readMovieSizeFromPath:currentMovie.File_path];
//    
//	double contLeng=[currentMovie movieContentLength];
	cell.sizelabel.text=[NSString stringWithFormat:@"%@%.2f ％",LS(@"下载中"),100*newProgress];
	
}

#pragma mark tool
-(void)playMov:(UIButton*)sender{
    Movie*temp=[finishedArray objectAtIndex:sender.tag];
    if ([[temp Type] intValue] == MovieChannelTypePic) {
		PicShowViewController*picshow=[[PicShowViewController alloc] init];
		picshow.imgCount=0;
		picshow.picListArray=[NSArray arrayWithObject:temp];
		[self.navigationController pushViewController:picshow animated:YES];
		[picshow release];
	}
	else {
		if ([[temp Type] intValue] == MovieChannelTypeSeries) {
            
            NSMutableArray *tmp = [NSMutableArray array];
            for (int i=0; i<[[temp File_path_array] count]; i++) {
                if ([[[temp File_path_array] objectAtIndex:i] isKindOfClass:[NSString class]]) {
                    if ([[[temp File_path_array] objectAtIndex:i] length]>5) {
                        [tmp addObject:[[temp File_path_array] objectAtIndex:i]];
                    }
                }
            }
            [temp setFile_path_array:tmp];
            
            [temp setOrderNUM:0];
        }
		[[NSNotificationCenter defaultCenter] postNotificationName:PLAYMOVIENOTIFICATION object:temp];
	}
}
//-(void)deleteFinished:(UIButton*)sender{
//    [finishedArray removeObjectAtIndex:sender.tag];
//    [UserDefaults setObject:finishedArray forKey:DOWNLOADED_LIST];
//    [finishedTable reloadData];
//}
-(void)stateChange:(UIButton*)sender{
    DownLoadingCell*cell=(DownLoadingCell*)[downloadTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
   Movie* mov= [downloadArray objectAtIndex:sender.tag];
    if (mov.statusCode==0||mov.statusCode==1) {
        mov.statusCode=2;
         NSLog(@"replaceObjectAtIndex 4");

        [downloadArray replaceObjectAtIndex:sender.tag withObject:mov];
        [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
        cell.statelabel.text=LS(@"已暂停");
        [sender setTitle:LS(@"继续") forState:UIControlStateNormal];
        if (![self hasDownloadingMovie]) {
            [currentRequest clearDelegatesAndCancel];
            currentRequest=nil;
            Movie*m=nil;
            for (int i=0; i<downloadArray.count; i++) {
                Movie*temp=[downloadArray objectAtIndex:i];
                if (temp.statusCode==1) {
                    m=temp;
                    break;
                }
            }
            if (m!=nil) {
                [self startDownload:m];
            }
        }
    }
    else {
        [currentRequest clearDelegatesAndCancel];
        currentRequest=nil;

        mov.statusCode=0;
        for (int  i=0;i<downloadArray.count;i++) {
            Movie*m=[downloadArray objectAtIndex:i];

            if (m.statusCode==0) {
                m.statusCode=2;
                 NSLog(@"replaceObjectAtIndex 5");

                [downloadArray replaceObjectAtIndex:i withObject:m];
            }
        }
        [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
        currentMovie=mov;
        cell.statelabel.text=LS(@"正在下载");
        [sender setTitle:LS(@"暂停") forState:UIControlStateNormal];
        [self startDownload:currentMovie];
        currentRequest.downloadProgressDelegate=self;
    }
    [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
    [downloadTable reloadData];
}
-(void)deletedownloadMovie:(UIButton*)sender{
    [currentRequest clearDelegatesAndCancel];
    currentRequest=nil;
    [[NSFileManager defaultManager] removeItemAtPath:[self tempPath:[[downloadArray objectAtIndex:sender.tag] File_path] ] error:nil];
    [downloadArray removeObjectAtIndex:sender.tag];
    [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
    Movie*m=nil;
    for (int i=0; i<downloadArray.count; i++) {
        Movie*temp=[downloadArray objectAtIndex:i];
        if (temp.statusCode==1) {
            m=temp;
            break;
        }
    }
    if (m!=nil) {
        [self startDownload:m];
    }
    [downloadTable reloadData];
}

-(BOOL)chechMovie:(id)item{
    NSArray* dArray=[UserDefaults objectForKey:DOWNLOADING_LIST];
    NSArray* fArray=[UserDefaults objectForKey:DOWNLOADED_LIST];
	for (id movie in dArray) {
		if ([[movie File_path] isEqualToString:[item File_path]]) {
			return YES;
		}
	}
	for (id movie in fArray) {
		if ([[movie File_path] isEqualToString:[item File_path]]) {
			return YES;
		}
	}
	return NO;
}
-(NSString*)destPath:(NSString*)filePath{
    NSString *destPath = [DOWNLOADED_VIDEOS_PATH stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[filePath lastPathComponent]]];
    return destPath;
}
-(NSString*)tempPath:(NSString*)filePath{
    NSString *tempPath=[[self destPath:filePath] stringByAppendingPathExtension:@"temp"];
    return tempPath;
}

-(double)readMovieSizeFromPath:(NSString*)filePath{
	BOOL a=[[NSFileManager defaultManager] fileExistsAtPath:[self tempPath:filePath]];
	BOOL b=[[NSFileManager defaultManager] fileExistsAtPath:[self destPath:filePath]];
	if (a) {
		NSDictionary* dic=[[NSFileManager defaultManager] attributesOfItemAtPath:[self tempPath:filePath] error:nil];
		long long int filesize=[dic fileSize];
		double contentLength = (double)filesize/1024.0/1024.0;
		return contentLength;
	}
    if (b) {
        NSDictionary* dic=[[NSFileManager defaultManager] attributesOfItemAtPath:[self destPath:filePath] error:nil];
		long long int filesize=[dic fileSize];
		double contentLength = (double)filesize/1024.0/1024.0;
		return contentLength;
    }
    return 0.0;
}
#pragma mark table
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  	static NSString* downloadIdentifier = @"downloadIdentifier";
//	static NSString* finishedIdentifier = @"finishedIdentifier";

//    if (tableView==finishedTable) {
//        DownLoadingCell* cell = (DownLoadingCell*)[tableView dequeueReusableCellWithIdentifier:finishedIdentifier];
//		if (cell == nil)
//		{
//			cell = [[[DownLoadingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:finishedIdentifier] autorelease];
//		}
//        Movie*fMov=[finishedArray objectAtIndex:indexPath.row];
//        double size=[self readMovieSizeFromPath:[self destPath:[fMov File_path]]];
//        cell.statelabel.text=LS(@"下载完成");
//        cell.sizelabel.text=[NSString stringWithFormat:@"%@ %.1f M",LS(@"大小:"),size];
//        cell.progressView.hidden=YES;
//        cell.downloadTitle.text=[fMov News_title];
//		cell.cellimage.image=[fMov iconImg];
//        [cell.fabu setTitle:LS(@"播放") forState:UIControlStateNormal];
//        [cell.shanchu setTitle:LS(@"删除") forState: UIControlStateNormal];
//        cell.shanchu.tag=indexPath.row;
//        cell.fabu.tag=indexPath.row;
//        [cell.fabu addTarget:self action:@selector(playMov:) forControlEvents:UIControlEventTouchUpInside];
//        [cell.shanchu addTarget:self action:@selector(deleteFinished:) forControlEvents:UIControlEventTouchUpInside];
//
//        return cell;
//    }else {
        DownLoadingCell* cell = (DownLoadingCell*)[tableView dequeueReusableCellWithIdentifier:downloadIdentifier];
		if (cell == nil)
		{
			cell = [[[DownLoadingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:downloadIdentifier] autorelease];
		}
		cell.fabu.tag=indexPath.row;
        
		Movie*movie=(Movie*)[downloadArray objectAtIndex:indexPath.row];
        
        double size=[self readMovieSizeFromPath:[self tempPath: [movie File_path]]];
        cell.statelabel.textColor=[UIColor greenColor];
        cell.progressView.progress=(float)size/movie.movieContentLength;
         NSLog(@"index %d size %f",indexPath.row,size);
        if (size>0) {
            cell.sizelabel.text=[NSString stringWithFormat:@"%@%.2f ％",LS(@"下载中"),100*size/movie.movieContentLength];
        }else{
            cell.sizelabel.text=[NSString stringWithFormat:@"%@0.00 ％",LS(@"下载中")];
            cell.progressView.progress=0;
        }
        if (movie.statusCode==0) {
            cell.statelabel.text=LS(@"正在下载");
        }else if(movie.statusCode==2){
            cell.statelabel.text=LS(@"已暂停");
        }else if (movie.statusCode==3) {
            cell.statelabel.textColor=[UIColor redColor];
            cell.statelabel.text=LS(@"下载失败");
        }else {
            cell.statelabel.text=LS(@"等待下载");
            cell.progressView.progress=0;
        }
        
        cell.downloadTitle.text=[movie News_title];

		cell.cellimage.image=[movie iconImg];
        
       if (movie.statusCode==0||movie.statusCode==1) {
            [cell.fabu setTitle:LS(@"暂停") forState:UIControlStateNormal];
       }else {
           [cell.fabu setTitle:LS(@"继续") forState:UIControlStateNormal];
       }
        cell.fabu.tag=indexPath.row;
        cell.shanchu.tag=indexPath.row;
        [cell.fabu addTarget:self action:@selector(stateChange:) forControlEvents:UIControlEventTouchUpInside];
		[cell.shanchu addTarget:self action:@selector(deletedownloadMovie:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
//    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (tableView==finishedTable) {
//        return finishedArray.count;
//    }else {
        return downloadArray.count;
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}
#pragma mark init 

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)dealloc{
    [finishedArray release];
    [downloadArray release];
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(downMovie:)
													 name:SENDTODOWNLOAD_NOTIFICATION 
												   object:nil];
        finishedArray= [[NSMutableArray alloc]initWithArray:[UserDefaults objectForKey:DOWNLOADED_LIST]];
		downloadArray=[[NSMutableArray alloc] initWithArray:[UserDefaults objectForKey:DOWNLOADING_LIST]];
        for (int i=0; i<downloadArray.count; i++) {
            Movie* mov=[downloadArray objectAtIndex:i];
            if (mov.statusCode==0) {
                mov.statusCode=2;
            }
             NSLog(@"replaceObjectAtIndex 6");

            [downloadArray replaceObjectAtIndex:i withObject:mov];
        }
        if (downloadArray.count) {
            [UserDefaults setObject:downloadArray forKey:DOWNLOADING_LIST];
        }
        [self initTable];
//		[self initTopView];

    }
    return self;
}
-(void)initTable{
    downloadTable=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460-44-49) style:UITableViewStylePlain];
    downloadTable.dataSource=self;
    downloadTable.delegate=self;
    downloadTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    downloadTable.backgroundColor=[UIColor clearColor];
    downloadTable.opaque=NO;
    downloadTable.allowsSelection=NO;
    [self.view addSubview:downloadTable];
    [downloadTable release];
//	downloadTable.hidden=YES;
	
//	finishedTable=[[UITableView alloc] initWithFrame:CGRectMake(0, 40, 320, 460-44-49-40) style:UITableViewStylePlain];
//    finishedTable.dataSource=self;
//    finishedTable.delegate=self;
//    finishedTable.separatorStyle=UITableViewCellSeparatorStyleNone;
//    finishedTable.backgroundColor=[UIColor clearColor];
//    finishedTable.opaque=NO;
//    finishedTable.allowsSelection=NO;
//    [self.view addSubview:finishedTable];
//    [finishedTable release];
	
}
- (void)initTopView
{
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:LS(@"已下载"),LS(@"正在下载"),nil]];
	segmentControl.frame = CGRectMake(10, 7, 140, 26);
    segmentControl.tintColor = TOOLBAR_TINTCOLOR;
	[segmentControl setSegmentedControlStyle:UISegmentedControlStyleBar];
	[segmentControl setSelectedSegmentIndex:0];
	[segmentControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
	[self.view addSubview:segmentControl];
	[segmentControl release];
    
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 39, 320, 2)];
    line.image = [UIImage imageNamed:@"fengexian.png"];
    [self.view addSubview:line];
    [line release];
}
//-(void)segmentChanged:(UISegmentedControl*)sender{
//	if (sender.selectedSegmentIndex==0) {
//        finishedTable.hidden=NO;
//		downloadTable.hidden=YES;
//		[finishedTable reloadData];
//        
//	}else {
//        currentRequest.downloadProgressDelegate = self;//下载进度代理
//        finishedTable.hidden=YES;
//		downloadTable.hidden=NO;
//		[downloadTable reloadData];
//    }
//}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
